package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.AllyActivateReward20;
import com.yourenbang.lingyun.domain.AllyActivateReward20Example;
import com.yourenbang.lingyun.domain.UserBase;
import com.yourenbang.lingyun.mapper.AllyActivateReward20Mapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.mapper.UserBaseMapper;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTableDateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTablePageDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.AppUserActivate;
import com.yourenbang.lingyun.transaction.web.service.migrate.AllyActivateRewardBatchMigrateService;
import com.yourenbang.lingyun.transaction.web.service.migrate.AllyActivateRewardMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AllyActivateRewardBatchMigrateServiceImpl extends AbstractMigrateService implements AllyActivateRewardBatchMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private AcmTransactionParams acmTransactionParams;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private CommonMigrateServiceImpl commonMigrateService;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private AllyActivateRewardMigrateService allyActivateRewardMigrateService;
    @Autowired
    private AllyActivateReward20Mapper allyActivateReward20Mapper;

    @Override
    public boolean migrateActiveRewardPage(QueryTablePageDTO dto) {
        String uri = "/query/pay/base/query/limit";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;
        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<AppUserActivate> appUserActivateList = jsonArray.toJavaList(AppUserActivate.class);

        saveActiveReward(appUserActivateList);
        return true;
    }

    @Override
    public boolean migrateActiveRewardOrder(QueryTableDateDTO dto) {
        String uri = "/query/pay/base/query/order";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;

        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<AppUserActivate> appUserActivateList = jsonArray.toJavaList(AppUserActivate.class);

        updateActiveReward(appUserActivateList);
        return true;
    }


    /**
     * 批量插入激活返现
     *
     * @param appUserActivateList
     */
    private void saveActiveReward(List<AppUserActivate> appUserActivateList) {
        List<AllyActivateReward20> allyActivateReward20List = new ArrayList<>();
        for (AppUserActivate appUserActivate : appUserActivateList) {
            try {
                UserBase fromUserBase = getUserBase(userBaseMapper, userBaseExtMapper, appUserActivate.getFromUserId(), redis);
                if (fromUserBase == null) {
                    KLog.error("[商户-考拉快收-数据迁移]激活返现更新,未获取到凌云用户fromUserBase,入参:{}", appUserActivate.toJSON());
                    throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户fromUserBase");
                }

                UserBase toUserBase = getUserBase(userBaseMapper, userBaseExtMapper, appUserActivate.getToUserId(), redis);
                if (toUserBase == null) {
                    KLog.error("[商户-考拉快收-数据迁移]激活返现更新,未获取到凌云用户toUserBase,入参:{}", appUserActivate.toJSON());
                    throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户toUserBase");
                }
                AllyActivateReward20 allyActivateReward20 = allyActivateRewardMigrateService
                        .fmtAllyActivateReward20Data(appUserActivate, fromUserBase, toUserBase);
                if (Objects.isNull(allyActivateReward20.getType())){
                    KLog.error("迁移商户激活返现失败,记录:{}", appUserActivate);
                    continue;
                }
                if (Objects.isNull(allyActivateReward20.getToRole())) {
                    allyActivateReward20.setToRole("0");
                }
                    allyActivateReward20List.add(allyActivateReward20);
                } catch (Exception e) {
                KLog.error("迁移商户激活返现失败,记录:{}", appUserActivate, e);
            }
        }
        if (allyActivateReward20List.size() != 0) {
            int i = allyActivateReward20Mapper.batchInsert(allyActivateReward20List);
            KLog.info("共[{}]条,插入[{}]条激活返现记录结束", allyActivateReward20List.size(), i);
        }
    }

    private void updateActiveReward(List<AppUserActivate> appUserActivateList) {
        List<AllyActivateReward20> allyActivateReward20List = new ArrayList<>();
        for (AppUserActivate appUserActivate : appUserActivateList) {
            try {
                UserBase fromUserBase = getUserBase(userBaseMapper, userBaseExtMapper, appUserActivate.getFromUserId(), redis);
                if (fromUserBase == null) {
                    KLog.error("[商户-考拉快收-数据迁移]激活返现更新,未获取到凌云用户fromUserBase,入参:{}", appUserActivate.toJSON());
                    throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户fromUserBase");
                }
                UserBase toUserBase = getUserBase(userBaseMapper, userBaseExtMapper, appUserActivate.getToUserId(), redis);
                if (toUserBase == null) {
                    KLog.error("[商户-考拉快收-数据迁移]激活返现更新,未获取到凌云用户toUserBase,入参:{}", appUserActivate.toJSON());
                    throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户toUserBase");
                }
                AllyActivateReward20Example reward20Example = new AllyActivateReward20Example();
                reward20Example.createCriteria()
                        .andFromUserBaseIdEqualTo(fromUserBase.getUserBaseId())
                        .andToRoleEqualTo(appUserActivate.getToRoleId())
                        .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(appUserActivate.getProductType()).getCode())
                        .andTypeEqualTo(appUserActivate.getType())
                        .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                List<AllyActivateReward20> allyActivateRewardList = allyActivateReward20Mapper.selectByExample(reward20Example);
                AllyActivateReward20 allyActivateReward20 = allyActivateRewardMigrateService
                        .fmtAllyActivateReward20Data(appUserActivate, fromUserBase, toUserBase);
                if(CollectionUtils.isEmpty(allyActivateRewardList)){
                    allyActivateReward20List.add(allyActivateReward20);
                }else {
                    allyActivateReward20.setAllyActivateRewardId(allyActivateRewardList.get(0).getAllyActivateRewardId());
                    int i = allyActivateReward20Mapper.updateByPrimaryKeySelective(allyActivateReward20);
                    BizAssertUtils.assertOne(i, "更新返现表失败");
                }
            } catch (Exception e) {
                KLog.error("更新激活返现表失败,数据:{}", appUserActivate, e);
            }

        }
        if (allyActivateReward20List.size() != 0) {
            int i = allyActivateReward20Mapper.batchInsert(allyActivateReward20List);
            KLog.info("[按时间更新激活返现]插入了{}条,共{}条", i, allyActivateReward20List.size());
        }
    }

}
